/*
 * @Author: lichao 1246877006@qq.com
 * @Date: 2025-07-03 21:36:17
 * @LastEditors: lichao 1246877006@qq.com
 * @LastEditTime: 2025-07-03 21:49:11
 * @FilePath: \2.decorator\9.ts
 * @Description:
 *
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved.
 */
// 方法装饰器还可以实现缓存结果
function cache(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  const cacheMap = new Map<string, number>()
  descriptor.value = function (...args: any[]) {
    // console.log("🚀 ~ cache ~ args:", args)
    const key = JSON.stringify(args);
    if (cacheMap.has(key)) {
      return cacheMap.get(key);
    } else {
      const result = originalMethod.apply(this, args);
      cacheMap.set(key, result);
      return result;
    }
  }
  return descriptor
}

class MathOperations {
  @cache
  factorial(n: number): number {
    if(n <= 1) return 1;
    return n * this.factorial(n - 1);
  }
}

const mathOperations = new MathOperations();
// console.timeStamp()
console.time()
console.log(mathOperations.factorial(20));
console.log(mathOperations.factorial(20));
// console.log(console)
console.timeEnd()
